//
// Created by xbm on 23-3-9.
//

#include "worker.h"
#include <mutex>
#include <thread>
#include <sstream>
#include "log.h"

using namespace std;
using namespace chrono;

using namespace threadPool;

void Worker::operator()() {
    stringstream ss;
    ss << "worker start working in thread " << this_thread::get_id();
    log(ss.view());

    mutex mx;
    unique_lock ul(mx);
    while (!done_) {
        cv_.wait_for(ul, 300ms);
        while (auto job = jobs_.pop()) {
            (**job)();//*job->JOB_TYPE, **job->packaged_task
        }
    }
    ss.str("");
    ss << "worker end working in thread " << this_thread::get_id();
    log(ss.view());
}

void Worker::commit(Worker::JOB_TYPE job) {
    jobs_.push(job);
    cv_.notify_one();
}

void Worker::finish() {
    stringstream ss;
    ss << "worker close running in thread " << this_thread::get_id();
    log(ss.view());
    if (!done_)
        done_ = true;
}

Worker::Worker() {
    stringstream ss;
    ss << "worker start running in thread " << this_thread::get_id();
    log(ss.view());
}

Worker::~Worker() {
    stringstream ss;
    ss << "worker end running in thread " << this_thread::get_id();
    log(ss.view());
}
